package com.snail.snailvr.views.fragments;

import android.app.Activity;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.snail.snailvr.R;
import com.snail.snailvr.VRApp;
import com.snail.snailvr.event.BusProvider;
import com.snail.snailvr.event.UpdateDownloadState;
import com.snail.snailvr.model.BannerModel;
import com.snail.snailvr.model.BaseData;
import com.snail.snailvr.model.DownloadInfoChangeEvent;
import com.snail.snailvr.model.Tag;
import com.snail.snailvr.model.VideoInfo;
import com.snail.snailvr.mvp.presenter.DiscoverPresenter;
import com.snail.snailvr.mvp.views.BaseView;
import com.snail.snailvr.network.providers.downloads.DownloadManager;
import com.snail.snailvr.utils.LogUtils;
import com.snail.snailvr.utils.Util;
import com.snail.snailvr.views.adapter.DiscoverAdapter;
import com.snail.snailvr.widget.WrapContentLinearLayoutManager;
import com.squareup.otto.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * 发现页面
 * Created by snail on 16/4/14.
 */
public class DiscoverFragment extends BaseDownloadFragment implements SwipeRefreshLayout.OnRefreshListener, BaseView {
    @Bind(R.id.loading_circle)
    View mLoadingView;
    @Bind(R.id.empty_view)
    TextView mEmptyView;
    @Bind(R.id.swipeRefreshLayout)
    SwipeRefreshLayout mSwipeRefreshLayout;
    @Bind(R.id.recycler_view)
    RecyclerView mRecyclerView;
    private List<VideoInfo> mVideoInfoList;
    private DiscoverAdapter mDiscoverAdapter;

    //首頁刪除下載中的視頻通知發現頁面更新
    @Subscribe
    public void updataDownloadState(UpdateDownloadState updateDownloadState) {
        updateDownloadState(updateDownloadState.getVideoId());
        LogUtils.d("update Discover DownloadState");
    }

    @Subscribe
    public void onDownloadInfoChange(DownloadInfoChangeEvent event) {
        downloadInfoChange(event);
    }

    @Override
    protected void handleIntent() {

    }

    @Override
    protected void initView() {
        mSwipeRefreshLayout.setOnRefreshListener(this);
        mSwipeRefreshLayout.setColorSchemeColors(getResources().getColor(R.color.positive_normal_color));
        setupRecyclerView();

    }

    private void setupRecyclerView() {
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(new WrapContentLinearLayoutManager(getActivity()));
        mVideoInfoList = new ArrayList<>();
        mDiscoverAdapter = new DiscoverAdapter(getActivity(), mVideoInfoList);
        mRecyclerView.setAdapter(mDiscoverAdapter);
    }

    @Override
    protected void loadData() {
        new DiscoverPresenter(this).loadData();
    }



    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        loadWhenUserVisible(isVisibleToUser);
    }

    protected void loadWhenUserVisible(boolean isVisibleToUser) {
        if (isVisibleToUser) {
            if (!this.isFragmentVisible) {
                loadData();
                this.isFragmentVisible = true;
            }
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_discover;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        VRApp.getRequestQueue().cancelAll(Tag.TAG_LIVE_BANNER);
    }

    @Override
    public void onRefresh() {
        loadData();
    }

    @Override
    protected RecyclerView getRecyclerView() {
        return mRecyclerView;
    }

    @Override
    protected RecyclerView.Adapter getAdapter() {
        return mDiscoverAdapter;
    }

    @Override
    protected List<VideoInfo> getVideoInfoList() {
        return mVideoInfoList;
    }

    @Override
    public void onResume() {
        super.onResume();

        BusProvider.getInstance().register(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        BusProvider.getInstance().unregister(this);
    }

    @Override
    public void showLoading() {
        mLoadingView.setVisibility(View.VISIBLE);
    }

    @Override
    public void hideLoading() {
        if (getActivity() == null) return;
        hideLoading(mSwipeRefreshLayout, mLoadingView);
    }

    @Override
    public void showEmpty() {

    }

    @Override
    public void showError() {
        if (getActivity() == null) return;
        hideLoading(mSwipeRefreshLayout, mLoadingView);
        hideLoading(mSwipeRefreshLayout, mLoadingView);
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mEmptyView.setVisibility(View.VISIBLE);
                Util.setDrawableTop(mEmptyView, R.drawable.ic_network_error);
                mSwipeRefreshLayout.setRefreshing(false);
            }
        });
    }

    @Override
    public void onRequestComplete(BaseData data) {
        mVideoInfoList.clear();
        mSwipeRefreshLayout.setRefreshing(false);
        mEmptyView.setVisibility(View.GONE);
        BannerModel bannerModel = (BannerModel) data;
        mVideoInfoList.addAll(bannerModel.getBannerList());
        mDiscoverAdapter.notifyDataSetChanged();
        updateDownloadState();
    }

    @Override
    public Activity getContext() {
        return getActivity();
    }

    /**
     * 更新videoId这个视频的下载状态
     */
    protected void updateDownloadState(final long videoId) {
        synchronized (mVideoInfoList) {
            Observable.from(mVideoInfoList).map(new Func1<VideoInfo, Boolean>() {
                @Override
                public Boolean call(VideoInfo videoInfo) {
                    if (videoInfo != null&&videoInfo.getVideoId()==videoId) {
                        videoInfo.setDownloadState(DownloadManager.STATUS_INIT);
                        return true;
                    }
                    return false;
                }
            }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<Boolean>() {
                @Override
                public void call(Boolean success) {
                    if(success)
                        mDiscoverAdapter.notifyDataSetChanged();
                }
            });
        }
    }
}
